/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * zEditServiceList.java
 *
 * Created on Oct 31, 2011, 6:44:27 PM
 */
package introsemp;
import java.sql.*;
import javax.swing.table.*;
import java.io.*;
/**
 *
 * @author G
 */
public class Form_Services extends javax.swing.JFrame {

    /** Creates new form zEditServiceList */
    Form_MainMenu menu;
    DefaultTableModel table;
    public Form_Services(Form_MainMenu menuGet) {
    
        menu=menuGet;
        initComponents();
        table=(DefaultTableModel)ServicesTable.getModel();
        try{
        PreparedStatement pstmt= menu.con.prepareStatement("SELECT * FROM services");
        ResultSet allTerminals= pstmt.executeQuery();
       while(allTerminals.next()){
           Integer num=allTerminals.getInt("ServiceCode");
           String name=allTerminals.getString("ServiceName");
           float price = allTerminals.getFloat("ServicePrice");
           boolean active = allTerminals.getBoolean("StatusBoolean");
           if(active)
           table.addRow(new Object[]{num,name,price,"Active"});
           else table.addRow(new Object[]{num,name,price,"Not Active"});
        } 
        }
        catch(SQLException ex){
            System.out.println("nada");
        }
        table=(DefaultTableModel)ServicesTable.getModel();
        
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        AddDialog = new javax.swing.JDialog();
        Name = new javax.swing.JLabel();
        NameField = new javax.swing.JTextField();
        Price = new javax.swing.JLabel();
        PriceField = new javax.swing.JTextField();
        AddDialogAdd = new javax.swing.JButton();
        AddDialogCancel = new javax.swing.JButton();
        SaveComplete = new javax.swing.JDialog();
        SaveFailed = new javax.swing.JDialog();
        TextFileComplete = new javax.swing.JDialog();
        TextFileFailed = new javax.swing.JDialog();
        ServicesPane = new javax.swing.JScrollPane();
        ServicesTable = new javax.swing.JTable();
        MatrixServicesList = new javax.swing.JLabel();
        DeleteService = new javax.swing.JButton();
        AddService = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        AddDialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        AddDialog.setTitle("Add Service");
        AddDialog.setAlwaysOnTop(true);
        AddDialog.setMinimumSize(new java.awt.Dimension(277, 185));
        AddDialog.setResizable(false);

        Name.setFont(new java.awt.Font("Tahoma", 0, 14));
        Name.setText("Name :");

        NameField.setFont(new java.awt.Font("Tahoma", 0, 12));
        NameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NameFieldActionPerformed(evt);
            }
        });

        Price.setFont(new java.awt.Font("Tahoma", 0, 14));
        Price.setText("Price  :");

        PriceField.setFont(new java.awt.Font("Tahoma", 0, 12));

        AddDialogAdd.setText("Add");
        AddDialogAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddDialogAddActionPerformed(evt);
            }
        });

        AddDialogCancel.setText("Cancel");
        AddDialogCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddDialogCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout AddDialogLayout = new javax.swing.GroupLayout(AddDialog.getContentPane());
        AddDialog.getContentPane().setLayout(AddDialogLayout);
        AddDialogLayout.setHorizontalGroup(
            AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AddDialogLayout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(AddDialogLayout.createSequentialGroup()
                        .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Price)
                            .addComponent(Name))
                        .addGap(18, 18, 18)
                        .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(PriceField)
                            .addComponent(NameField, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE))
                        .addGap(24, 24, 24))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, AddDialogLayout.createSequentialGroup()
                        .addComponent(AddDialogAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(62, 62, 62)
                        .addComponent(AddDialogCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(56, 56, 56))))
        );
        AddDialogLayout.setVerticalGroup(
            AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AddDialogLayout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Name)
                    .addComponent(NameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Price)
                    .addComponent(PriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addGroup(AddDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AddDialogAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(AddDialogCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(66, Short.MAX_VALUE))
        );

        SaveComplete.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout SaveCompleteLayout = new javax.swing.GroupLayout(SaveComplete.getContentPane());
        SaveComplete.getContentPane().setLayout(SaveCompleteLayout);
        SaveCompleteLayout.setHorizontalGroup(
            SaveCompleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        SaveCompleteLayout.setVerticalGroup(
            SaveCompleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        SaveFailed.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout SaveFailedLayout = new javax.swing.GroupLayout(SaveFailed.getContentPane());
        SaveFailed.getContentPane().setLayout(SaveFailedLayout);
        SaveFailedLayout.setHorizontalGroup(
            SaveFailedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        SaveFailedLayout.setVerticalGroup(
            SaveFailedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        TextFileComplete.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout TextFileCompleteLayout = new javax.swing.GroupLayout(TextFileComplete.getContentPane());
        TextFileComplete.getContentPane().setLayout(TextFileCompleteLayout);
        TextFileCompleteLayout.setHorizontalGroup(
            TextFileCompleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        TextFileCompleteLayout.setVerticalGroup(
            TextFileCompleteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        TextFileFailed.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout TextFileFailedLayout = new javax.swing.GroupLayout(TextFileFailed.getContentPane());
        TextFileFailed.getContentPane().setLayout(TextFileFailedLayout);
        TextFileFailedLayout.setHorizontalGroup(
            TextFileFailedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        TextFileFailedLayout.setVerticalGroup(
            TextFileFailedLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Matrix Services List");
        setName("ServicesListFrame"); // NOI18N
        setResizable(false);

        ServicesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Service Number", "Name", "Price", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Float.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        ServicesTable.setRowSelectionAllowed(false);
        ServicesTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                ServicesTableMouseExited(evt);
            }
        });
        ServicesPane.setViewportView(ServicesTable);

        MatrixServicesList.setFont(new java.awt.Font("Tahoma", 0, 18));
        MatrixServicesList.setText("Matrix Services List");

        DeleteService.setText("Delete");
        DeleteService.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteServiceActionPerformed(evt);
            }
        });

        AddService.setText("Add");
        AddService.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddServiceActionPerformed(evt);
            }
        });

        jButton1.setText("Change Status");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Generate Text File");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(245, 245, 245)
                .addComponent(MatrixServicesList)
                .addContainerGap(247, Short.MAX_VALUE))
            .addComponent(ServicesPane, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(AddService)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(5, 5, 5)
                .addComponent(DeleteService)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(277, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(MatrixServicesList)
                .addGap(18, 18, 18)
                .addComponent(ServicesPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AddService)
                    .addComponent(DeleteService)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_NameFieldActionPerformed

    private void AddDialogAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddDialogAddActionPerformed
        // TODO add your handling code here:
        int code=0;
        try{
        PreparedStatement pstmt= menu.con.prepareStatement("SELECT * FROM services");
        ResultSet id= pstmt.executeQuery();
       while(id.next()){
            if(code+1==id.getInt("ServiceCode"))code=id.getInt("ServiceCode");
        } 
        }
        catch(SQLException ex){
            System.out.println("nada");
        }
        
        try{
        System.out.println("Add");
        code++;
        String max=Integer.toString(code);
        PreparedStatement pstmt =
                menu.con.prepareStatement("INSERT INTO `services` (`ServiceCode`, `ServiceName`, `ServicePrice`, `StatusBoolean`) VALUES (?, ?, ?, ?)");
            //append values for the parameters
            int i=1;
            pstmt.setString(i++, max);
            pstmt.setString(i++, NameField.getText());
            pstmt.setString(i++, PriceField.getText());
            pstmt.setString(i++, "1"); 
            pstmt.executeUpdate(); 
        
        while(table.getRowCount()!=0){
           table.removeRow(0); 
       }
        
        PreparedStatement pstmt2= menu.con.prepareStatement("SELECT * FROM services");
        ResultSet allTerminals= pstmt2.executeQuery();
       while(allTerminals.next()){
           Integer num=allTerminals.getInt("ServiceCode");
           String name=allTerminals.getString("ServiceName");
           float price = allTerminals.getFloat("ServicePrice");
           boolean active = allTerminals.getBoolean("StatusBoolean");
           if(active)
           table.addRow(new Object[]{num,name,price,"Active"});
           else table.addRow(new Object[]{num,name,price,"Not Active"});
        } 
    }
        catch(SQLException ex){
            System.out.println("nada");
             System.err.println("SQLState: " + ((SQLException)ex).getSQLState());
          System.err.println("Error Code: " + ((SQLException)ex).getErrorCode());
          System.err.println("Message: " + ex.getMessage());
        }
        
        AddDialog.dispose();
    }//GEN-LAST:event_AddDialogAddActionPerformed

    private void AddDialogCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddDialogCancelActionPerformed

        this.AddDialog.dispose();
    }//GEN-LAST:event_AddDialogCancelActionPerformed

    private void AddServiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddServiceActionPerformed
      this.AddDialog.setVisible(true);
        AddDialog.setSize(425, 250);
    }//GEN-LAST:event_AddServiceActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        Integer get=ServicesTable.getSelectedRow()+1;
        String max=Integer.toString(get);
        try{
        PreparedStatement pstmt= menu.con.prepareStatement("SELECT * FROM services where ServiceCode = ?");
         int i=1;
        pstmt.setString(i++,max);
        ResultSet getStatus=pstmt.executeQuery();
        getStatus.next();
        String status = getStatus.getString("StatusBoolean");
        System.out.println(status);
        if(status.equals("1")){
        PreparedStatement pstmt2 = menu.con.prepareStatement("UPDATE services SET StatusBoolean='0' WHERE ServiceCode=?");  
        i=1;
        pstmt2.setString(i++,max);
        pstmt2.executeUpdate();
        }
        else{
        PreparedStatement pstmt2 = menu.con.prepareStatement("UPDATE services SET StatusBoolean='1' WHERE ServiceCode=?");      
        i=1;
        pstmt2.setString(i++,max);
        pstmt2.executeUpdate();
        }
        
        while(table.getRowCount()!=0){
           table.removeRow(0); 
       }
        
        PreparedStatement pstmt2= menu.con.prepareStatement("SELECT * FROM services");
        ResultSet allTerminals= pstmt2.executeQuery();
       while(allTerminals.next()){
           Integer num=allTerminals.getInt("ServiceCode");
           String name=allTerminals.getString("ServiceName");
           float price = allTerminals.getFloat("ServicePrice");
           boolean active = allTerminals.getBoolean("StatusBoolean");
           if(active)
           table.addRow(new Object[]{num,name,price,"Active"});
           else table.addRow(new Object[]{num,name,price,"Not Active"});
        } 
        
        }
        catch(SQLException ex){
            System.out.println("nada");
             System.err.println("SQLState: " + ((SQLException)ex).getSQLState());
          System.err.println("Error Code: " + ((SQLException)ex).getErrorCode());
          System.err.println("Message: " + ex.getMessage());
            System.out.println("nada");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

private void DeleteServiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteServiceActionPerformed
// TODO add your handling code here:
        try{
        Integer get=ServicesTable.getSelectedRow();
        Integer nameGet=(Integer)ServicesTable.getValueAt(get,0);
        String number=Integer.toString(nameGet);
        PreparedStatement pstmt= menu.con.prepareStatement("delete from services where ServiceCode =?"); 
        int i=1;
        pstmt.setString(i++,number);
        pstmt.executeUpdate();

            
        
       
        while(table.getRowCount()!=0){
           table.removeRow(0); 
       }
        
        PreparedStatement pstmt2= menu.con.prepareStatement("SELECT * FROM services");
        ResultSet allTerminals= pstmt2.executeQuery();
       while(allTerminals.next()){
           Integer num=allTerminals.getInt("ServiceCode");
           String name=allTerminals.getString("ServiceName");
           Integer price = allTerminals.getInt("ServicePrice");
           boolean active = allTerminals.getBoolean("StatusBoolean");
           if(active)
           table.addRow(new Object[]{num,name,price,"Active"});
           else table.addRow(new Object[]{num,name,price,"Not Active"});
        } 
        
        }
        catch(SQLException ex){
            System.out.println("nada");
             System.err.println("SQLState: " + ((SQLException)ex).getSQLState());
          System.err.println("Error Code: " + ((SQLException)ex).getErrorCode());
          System.err.println("Message: " + ex.getMessage());
        }
}//GEN-LAST:event_DeleteServiceActionPerformed

private void ServicesTableMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ServicesTableMouseExited
// TODO add your handling code here:
}//GEN-LAST:event_ServicesTableMouseExited

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
     try {
          FileWriter outFile = new FileWriter("Services.txt");
             PrintWriter out = new PrintWriter(outFile);
        
                out.println("# Service List #");
                for(int x=0;x<table.getRowCount();x++){
                int num=(Integer)table.getValueAt(x,0);
                String name=(String)table.getValueAt(x,1);
                float price=(Float)table.getValueAt(x,2);
                String status=(String)table.getValueAt(x,3);
                out.println(num+" | "+name+" | "+price+" | "+status);
                }
                out.close();
        } catch (IOException e){
             e.printStackTrace();
         }// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        
        /* Create and display the form */
      

     
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDialog AddDialog;
    private javax.swing.JButton AddDialogAdd;
    private javax.swing.JButton AddDialogCancel;
    private javax.swing.JButton AddService;
    private javax.swing.JButton DeleteService;
    private javax.swing.JLabel MatrixServicesList;
    private javax.swing.JLabel Name;
    private javax.swing.JTextField NameField;
    private javax.swing.JLabel Price;
    private javax.swing.JTextField PriceField;
    private javax.swing.JDialog SaveComplete;
    private javax.swing.JDialog SaveFailed;
    private javax.swing.JScrollPane ServicesPane;
    private javax.swing.JTable ServicesTable;
    private javax.swing.JDialog TextFileComplete;
    private javax.swing.JDialog TextFileFailed;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration//GEN-END:variables
}
